using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Route;
using B.S.XZYData.Api.Read.Dto.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Route
{
    /// <summary>
    /// 获取工艺路线详情处理器（包含工序列表）
    /// </summary>
    public class GetRouteDetailHandler : IRequestHandler<GetRouteDetailCommand, ApiResult<RouteDetailDto>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepo;
        private readonly IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> _processRepo;
        private readonly IMapper _mapper;

        public GetRouteDetailHandler(
            IBaseRepository<RouteModel> routeRepo,
            IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> processRepo,
            IMapper mapper)
        {
            _routeRepo = routeRepo;
            _processRepo = processRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<RouteDetailDto>> Handle(GetRouteDetailCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<RouteDetailDto>();

            try
            {
                // 获取工艺路线
                var route = _routeRepo.GetAll()
                    .Where(x => x.Id == request.RouteId)
                    .ToList()
                    .FirstOrDefault();

                if (route == null)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "工艺路线不存在";
                    return res;
                }

                // 获取工序列表
                var processes = _processRepo.GetAll()
                    .Where(x => x.RoutdId == request.RouteId)
                    .ToList()
                    .OrderBy(x => x.ProcessNumber)
                    .ToList();

                // 调试日志
                Console.WriteLine($"查询路线ID: {request.RouteId}，找到工序数量: {processes.Count}");
                foreach (var process in processes)
                {
                    Console.WriteLine($"工序ID: {process.Id}, 工序编号: {process.ProcessNumber}, 工序名称: {process.ProcessName}, 路线ID: {process.RoutdId}");
                }

                // 映射到DTO
                var routeDetailDto = _mapper.Map<RouteDetailDto>(route);
                var stepDtos = _mapper.Map<List<RouteStepDto>>(processes);
                routeDetailDto.Steps = stepDtos;

                // 调试日志
                Console.WriteLine($"映射后的DTO工序数量: {stepDtos.Count}");
                foreach (var step in stepDtos)
                {
                    Console.WriteLine($"DTO - ID: {step.Id}, 工序编号: {step.ProcessCode}, 工序名称: {step.ProcessName}, 路线ID: {step.RouteId}");
                }

                res.Data = routeDetailDto;
                res.Code = ApiEnum.Success;
                res.Msg = "获取工艺路线详情成功";
            }
            catch (AutoMapperMappingException ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取工艺路线详情失败：映射异常 -> {ex.Message}";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取工艺路线详情失败：{ex.Message}";
            }

            return res;
        }
    }
} 